<?php
/**
 * The login controller 
 * 
 * @author Youssef Driouach
 *
 * 20 août 2012
 */
class LoginController extends Zend_Controller_Action{
	/**
	 * initilize the login controller with a specifique title.
	 * 
	 * @see Zend_Controller_Action::init()
	 */
	public function init() {
		$title ="Log in to our web site";
		$this->view->__set("headtitle", $title);
	    
	  }
	 
	  
	 
	  public function indexAction() {
	  	
	  	if(Zend_Auth::getInstance()->hasIdentity()){
	  		$this->_redirect('index');
	  	}
	  	
	   	$form = new Application_Form_Login ('loginform');
	    $this->view->form = $form;
	 
	    if ($this->_request->isPost()) {
	      $formData = $this->_request->getPost();
	      if ($form->isValid($formData) AND $form->getElement("submit")->getAttrib("test") == "") {
	        $email = $form->getValue('email');
	        $password = $form->getValue('password');
	        $authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table_Abstract::getDefaultAdapter());
	        $authAdapter->setTableName('user')
				        ->setIdentityColumn('email')
				        ->setCredentialColumn('password')
				        ->setCredentialTreatment('SHA1(?) AND status = 1')
				        ->setIdentity($email)
				        ->setCredential($password);
	        
	        // try to authenticate a user
	        $result = $authAdapter->authenticate();
	        
	        // is the user valid one?
	        switch ($result->getCode()) {
	        
	        	case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
	        		$this->view->error = 'Identity not found';
	        		break;
	        
	        	case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
	        		$this->view->error = 'Invalid credential';
	        		break;
	        
	        	case Zend_Auth_Result::SUCCESS:
	        		// get user object (ommit password_hash)
	        		$user = $authAdapter->getResultRowObject(null, 'password');
	        		
	        		
	        		// check if the user is approved
	        		
        			// to help thwart session fixation/hijacking
// 	        			if ($form->getValue('rememberMe') == 1) {
// 	        				// remember the session for 604800s = 7 days
// 	        				Zend_Session::rememberMe(604800);
// 	        			} else {
// 	        				// do not remember the session
// 	        				Zend_Session::forgetMe();
// 	        			}
        			// store user object in the session
        			$authStorage = Zend_Auth::getInstance()->getStorage();
        			$authStorage->write($user);
        			$this->_redirect('index');
	        		
	        		break;
	        
	        	default:
	        		$this->view->error = 'Wrong username and/or password';
	        		break;
	        }

	      }
	    }
	    $this->render ( 'index' );
	  }
	 
	 
	 
	  public function logoutAction() {
	    Zend_Auth::getInstance ()->clearIdentity ();
	    $this->_helper->redirector ( 'index', 'index' );
	  }
 
}